import { uniConfig } from '../config/UniConfig';
import { WebSocketAdaptor } from '../user/WebSocketAdaptor';
export class WebSocketGame {
  private static instance = null as unknown as WebSocketGame;
  private webSocketUrl = uniConfig.webSocketUrl;
  private isConnected = false;
  private messageQueueList = [];
  private webScoket: WebSocket = null;
  public static Instance() {
    if (!this.instance) {
      this.instance = new WebSocketGame();
    }
    
    return this.instance;
  }
  constructor() {
    this.reConstruct();
  }
  public reConstruct() {
    this.isConnected = false;
    this.messageQueueList = [];
    this.webSocketUrl = uniConfig.webSocketUrl;
    this.webScoket = new WebSocket(this.webSocketUrl);
    this.initEvent();
  }
  public initEvent() { // 初始化一些webSocket事件
    var that = this;
    this.webScoket.onopen = (event: MessageEvent) => {
      that.isConnected = true;
    };

    this.webScoket.onerror = (event: MessageEvent) => {
      that.closeSocket();
      that.isConnected = false;
      that.connectSocket();
    };

    this.webScoket.onclose = (event: CloseEvent) => {
      that.closeSocket();
      that.isConnected = false;
      that.connectSocket();
    };
    
    this.webScoket.onmessage = (event: MessageEvent) => {
      WebSocketAdaptor.Instance().processRecvMessage(event.data);
    }

    
    setInterval(() => {
      this.checkSendMessage();
    }, 3000);
  }
  public connectSocket() {
    this.reConstruct();
  }
  public closeSocket() {
    this.webScoket.close();
  }

  sendSocketMessage(data: string) {
    if (this.isConnected) {
      this.webScoket.send(data);
    } else {
      this.messageQueueList.push(data);
    }
  }

  checkSendMessage() {
    if (this.isConnected) {
      if (this.messageQueueList.length > 0) {
        var msg = this.messageQueueList.shift();
        this.sendSocketMessage(msg);
      }
    }
  }
}